//
//  UIColor+CW.m
//  CWDevelop
//
//  Created by LittoCats on 7/11/14.
//  Copyright (c) 2014 Littocats. All rights reserved.
//

#import "UIColor+CW.h"

#import "NSObject+CW.h"
#import <objc/message.h>

@implementation UIColor (CW)

- (NSString *)script
{
    CGFloat red,green,blue,alpha;
    
    [self getRed:&red green:&green blue:&blue alpha:&alpha];
    return [NSString stringWithFormat:@"#%.2X%.2X%.2X%.2X",(int)(red*255),(int)(green*255),(int)(blue*255),(int)(alpha*255)];
}

+ (UIColor *) colorWithScript:(NSString *)script
{
    if (!script || [script isEmpty]) {
        return nil;
    }
    
    if ([script hasPrefix:@"#"]) {
        return [UIColor colorWithHexString:script];
    }else{
        SEL selector = NSSelectorFromString([script stringByAppendingString:@"Color"]);
        if ([UIColor respondsToSelector:selector]) {
            return  objc_msgSend([UIColor class], selector);
        }
    }
    return [UIColor whiteColor];
}

+ (UIColor*)colorWithHexString:(NSString*)hexString{
    NSString *colorString = [[hexString stringByReplacingOccurrencesOfString: @"#" withString: @""] uppercaseString];
    CGFloat alpha, red, blue, green;
    char *p;
    NSUInteger hexValue = strtoul([colorString cStringUsingEncoding:NSUTF8StringEncoding], &p, 16);
    switch ([colorString length]) {
        case 3: // #RGB
            alpha = 1.0f;
            red = ((hexValue & 0xf00) >> 8) / 255.0;
            green = ((hexValue & 0xf0) >> 4) / 255.0;
            blue = (hexValue & 0xf) / 255.0;
            break;
        case 4: // #ARGB
            red = ((hexValue & 0xf000) >> 12) / 255.0;
            green = ((hexValue & 0xf00) >> 8) / 255.0;
            blue = ((hexValue & 0xf0) >> 4) / 255.0;
            alpha = (hexValue & 0xf) / 255.0;
            break;
        case 6: // #RRGGBB
            alpha = 1.0f;
            red = ((hexValue & 0xff0000) >> 16) / 255.0;
            green = ((hexValue & 0xff00) >> 8) / 255.0;
            blue = (hexValue & 0xff) / 255.0;
            break;
        case 8: // #AARRGGBB
            red = ((hexValue & 0xff000000) >> 24) / 255.0;
            green = ((hexValue & 0xff0000) >> 16) / 255.0;
            blue = ((hexValue & 0xff00) >> 8) / 255.0;
            alpha = (hexValue & 0xff) / 255.0;
            break;
        default:
            [NSException raise:@"Invalid color value" format: @"Color value %@ is invalid.  It should be a hex value of the form #RGB, #RGBA, #RRGGBB, or #RRGGBBAA", hexString];
            break;
    }
    return [UIColor colorWithRed: red green: green blue: blue alpha: alpha];
}
@end
